package top.cardone.context.util;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.CodeException;

import java.util.Map;

/**
 * Created by yht on 16-2-2.
 */
public class CodeExceptionUtils {
	private CodeExceptionUtils() {
	}

	public static Map<String, String> newMap(String url, String errorCode, String... errors) {
		Map<String, String> errorInfo = Maps.newHashMap();

		errorInfo.put("url", url);

		errorInfo.put("errorCode", errorCode);

		String error = org.apache.commons.lang3.StringUtils.join(errors);

		errorInfo.put("error", MessageUtils.getMessage("errorCode", errors, error));

		return errorInfo;
	}

	public static Map<String, String> newMap(String url, Exception ex) {
		Map<String, String> errorInfo = Maps.newHashMap();

		errorInfo.put("url", url);

		if (ex instanceof CodeException) {
			CodeException codeException = (CodeException) ex;

			errorInfo.put("errorCode", codeException.getMessage());


			String error = org.apache.commons.lang3.StringUtils.join(codeException.getArgs());

			errorInfo.put("error", MessageUtils.getMessage(codeException.getMessage(), codeException.getArgs(), error));
		} else {
			errorInfo.put("errorCode", "000000");
			errorInfo.put("error", ex.getMessage());
		}

		return errorInfo;
	}

	public static String newString(String url, String errorCode, String... errors) {
		Map<String, String> errorInfo = newMap(url, errorCode, errors);

		String json = ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);

		return json;
	}

	public static String newString(String url, Exception ex) {
		Map<String, String> errorInfo = newMap(url, ex);

		String json = ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);

		return json;
	}
}
